package org.ggumm21.moneybook.servlet;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.ggumm21.moneybook.BookManager;
import org.ggumm21.moneybook.MoneybookUser;

import com.google.appengine.api.NamespaceManager;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class GaeFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

    	User googleUser = UserServiceFactory.getUserService().getCurrentUser();
    	if (googleUser == null) {
    		throw new ServletException("User not logged-in");
    	}
    	String userId = googleUser.getUserId();
    	if (userId == null) {
    		throw new ServletException("UserId is null");
    	}

    	boolean needsUserInit = false;
    	MoneybookUser moneybookUser = null;
    	
	    NamespaceManager.set("");
		Objectify ofy = ObjectifyService.begin();

		BookManager.setDefaultTimezone();
		
		synchronized(this) {
			moneybookUser = ofy.find(MoneybookUser.class, userId);
			if (moneybookUser == null) {
				moneybookUser = new MoneybookUser(googleUser);
				ofy.put(moneybookUser);
				needsUserInit = true;		
			} else if (!moneybookUser.isInitialized()) {
				needsUserInit = true;				
			}
    	}
    	
		NamespaceManager.set(userId);
		
		if (needsUserInit) {
			if (BookManager.initMoneybookInstance(userId)) {
			    NamespaceManager.set("");
				ofy = ObjectifyService.begin();
				moneybookUser.setInitialized();
				ofy.put(moneybookUser);
				NamespaceManager.set(userId);
				HttpSession session = ((HttpServletRequest)request).getSession();
				if (session != null) session.invalidate();
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
